<script lang="jsx" setup>
import dayjs from 'dayjs';
import { nextTick, ref, watch } from 'vue';
import { UUID } from 'uuidjs';
import { getAddFeedBoardData } from '@/service/api/modules/work-order-management/production-feed';
import useResetTableRef from '@/hooks/common/resetTableRef';
import EngineeringInstruction from './engineering-instruction-inner.vue';

const props = defineProps({
  rowData: {
    type: Object,
    required: true
  },
  engineeringTableData: {
    type: Array,
    default: () => []
  },
  engineeringInstructionData: {
    type: Array,
    default: () => []
  }
});

const rowData = props.rowData;

const emit = defineEmits(['saveData']);

const commonSearchRef = ref(null);
const [searchParams, resetSearchParams] = useResetTableRef({
  specif7: null,
  specif6: null,
  specif3: null,
  color: null,
  height: null,
  specif10: null,
  specif8: null,
  specif9: null,
  width: null,
  length: null,
  specif14: null,
  specif15: null,
  special: null,
  matNo: null,
  specif: null,
  specif2: null,
  matReplace: null,
  materialType: 0
});
const formList = [
  {
    type: 'input',
    key: 'specif7',
    label: '底铜',
    span: 6,
    placeholder: ''
  },
  {
    type: 'input',
    key: 'specif6',
    label: '顶铜',
    span: 6,
    placeholder: ''
  },
  {
    type: 'input',
    key: 'specif3',
    label: '板材类型',
    span: 6,
    placeholder: ''
  },
  {
    type: 'input',
    key: 'color',
    label: '板材颜色',
    span: 6,
    placeholder: ''
  },
  {
    type: 'input',
    key: 'height',
    label: '板厚(mm)',
    span: 6,
    placeholder: ''
  },
  {
    type: 'input',
    key: 'specif10',
    label: 'TG值',
    span: 6,
    placeholder: ''
  },
  {
    type: 'input',
    key: 'specif8',
    label: 'CTI',
    span: 6,
    placeholder: ''
  },
  {
    type: 'input',
    key: 'specif9',
    label: '含铜',
    span: 6,
    placeholder: ''
  },
  {
    type: 'input',
    key: 'width',
    label: '宽',
    span: 6,
    placeholder: ''
  },
  {
    type: 'input',
    key: 'length',
    label: '长',
    span: 6,
    placeholder: ''
  },

  {
    type: 'input',
    key: 'specif14',
    label: '无卤素要求',
    span: 6,
    placeholder: ''
  },
  {
    type: 'input',
    key: 'specif15',
    label: '板料水印',
    span: 6,
    placeholder: ''
  },
  {
    type: 'input',
    key: 'special',
    label: '板料特殊要求',
    span: 8,
    placeholder: ''
  },
  {
    type: 'input',
    key: 'matNo',
    label: '物料编码',
    span: 8,
    placeholder: ''
  },
  {
    type: 'input',
    key: 'specif',
    label: '规格',
    span: 8,
    placeholder: ''
  },
  {
    type: 'input',
    key: 'specif2',
    label: '供应商',
    span: 8,
    placeholder: ''
  },
  {
    type: 'checkbox',
    key: 'matReplace',
    label: '',
    span: 8,
    placeholder: '',
    selectOptions: [
      {
        label: '代料',
        value: true
      }
    ]
  }
];

const leftTableRef = ref(null);

const leftColumn = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'matname',
    dataIndex: 'matname',
    title: '板材名称',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 120
  },
  {
    key: 'specif2',
    dataIndex: 'specif2',
    title: '供应商',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 120
  },
  {
    key: 'specif',
    dataIndex: 'specif',
    title: '物料规格',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 400,
    customRender: ({ record }) => {
      return record?.matSpecs?.replace(/黄料|黄色/g, '');
    }
  },
  {
    key: 'invqty',
    dataIndex: 'invqty',
    title: '库存数量',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 120
  },
  {
    key: 'occupancyqty',
    dataIndex: 'occupancyqty',
    title: '占用数量',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 120
  },
  {
    key: 'invQty-occupancyQty',
    dataIndex: 'invQty-occupancyQty',
    title: '可用库存数量',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 120,
    customRender: ({ record }) => {
      return record.invqty - record.occupancyqty;
    }
  },
  {
    key: 'proddate',
    dataIndex: 'proddate',
    title: '生产日期',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 120,
    customRender: ({ record }) => {
      return record.proddate && dayjs(record.proddate).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  {
    key: 'createdate',
    dataIndex: 'createdate',
    title: '入库日期',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 120,
    customRender: ({ record }) => {
      return record.createdate && dayjs(record.createdate).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  {
    key: 'unit',
    dataIndex: 'unit',
    title: '单位',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 120
  },
  {
    key: 'matno',
    dataIndex: 'matno',
    title: '板材编码',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 120
  },
  {
    key: 'length',
    dataIndex: 'length',
    title: '长',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 120
  },
  {
    key: 'width',
    dataIndex: 'width',
    title: '宽',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 120
  }
];

function getModelData() {
  const data = props.engineeringTableData[0];
  console.log('data ``````````', data);

  searchParams.value.specif7 = data.data1?.trim().split('/')[0];
  searchParams.value.specif6 = data.data1?.trim().split('/')[1];
  searchParams.value.height = data.data2;
  searchParams.value.specif9 = data.data5;

  const mouldIds = {
    specif3: '1350000048500041',
    color: '1350000048500044',
    specif10: '1350000048500051',
    specif8: '1350000048500053',
    width: '1350000048500012',
    length: '1350000048500011',
    special: '1350000048500040',
    specif14: '1350000048500088',
    specif15: '1350000048500045',
    specif2: '1350000048500037'
  };

  Object.keys(mouldIds).forEach(key => {
    const foundItem = props.engineeringInstructionData.find(item => item.miMouldId === mouldIds[key]);
    searchParams.value[key] =
      key === 'specif14' && (foundItem?.miData === '/' || foundItem?.miData === '//')
        ? null
        : foundItem?.miData || null;
  });
}

watch(
  () => [props.engineeringTableData, props.engineeringInstructionData],
  () => {
    getModelData();
  },
  {
    deep: true,
    immediate: true
  }
);

const dataSource = ref([]);
function getDataSource() {
  getAddFeedBoardData({
    ...searchParams.value,
    specif2: undefined
  }).then(({ data, error }) => {
    if (!error) {
      data.forEach((item, index) => {
        item.dataIndex = index + 1;
        item.tableUuid = UUID.genV4().hexNoDelim;
      });
      dataSource.value = data;
    }
  });
}

function search() {
  getDataSource();
}

function reset() {
  resetSearchParams();
  search();
}

const engineeringInstructionRef = ref(null);

function getData(params) {
  searchParams.value = {
    ...searchParams.value,
    ...params
  };
  getDataSource();
}

nextTick(() => {
  // 获取工程指示tab
  engineeringInstructionRef.value.getData({
    prodId: rowData.prodID,
    techId: rowData.techid
  });
});

const currentRow = ref([]);
function handleTableSelectChange(val) {
  currentRow.value = val[0];
}

function validateMI() {
  return (
    currentRow.value.length === searchParams.value.length &&
    currentRow.value.width === searchParams.value.width &&
    currentRow.value.specif3 === searchParams.value.specif3 &&
    currentRow.value.specif6 === searchParams.value.specif6 &&
    currentRow.value.specif7 === searchParams.value.specif7 &&
    currentRow.value.height === searchParams.value.height &&
    currentRow.value.specif9 === searchParams.value.specif9 &&
    currentRow.value.specif10 === searchParams.value.specif10
  );
}

function validateCTI() {
  const specif8 = currentRow.value.specif8?.trim() || '175';
  return specif8 === (searchParams.value.specif8 || '175');
}

function check() {
  if (!currentRow.value) {
    window.$message.error('请选择需要保存的行!');
    return false;
  }

  if (!searchParams.value?.matReplace?.includes(true)) {
    console.log('没有选择待料进行判断');

    if (!validateMI()) {
      window.$message.error('所选板材与MI信息不符,请重新选择!');
      return false;
    }

    if (!validateCTI()) {
      window.$message.error('所选板材与CTI不符,请重新选择!');
      return false;
    }

    if (currentRow.value.specif15 !== (searchParams.value.specif15 || '')) {
      window.$message.error('所选板材与板料水印不符,请重新选择!');
      return false;
    }
  }
  return true;
}

function saveData() {
  if (check()) {
    return currentRow.value;
  }
  return null;
}

defineExpose({
  getData,
  saveData
});
</script>

<template>
  <div class="h-full w-full">
    <ARow :gutter="16" class="h-full w-full">
      <ACol :span="14" class="h-full min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
        <CommonSearch
          ref="commonSearchRef"
          v-model:searchParams="searchParams"
          :form-list="formList"
          @search="search"
          @reset="reset"
        ></CommonSearch>
        <Table
          ref="leftTableRef"
          v-model:searchParams="searchParams"
          row-selection-type="radio"
          :show-card-header="false"
          :data-source="dataSource"
          :column="leftColumn"
          :show-row-selection="true"
          :auto-generate-uuid="false"
          row-key="tableUuid"
          :scroll="{ y: 'auto' }"
          is-init-get-data
          url=""
          class="h-full"
          :is-pagination="false"
          @table-select-change="handleTableSelectChange"
        ></Table>
      </ACol>
      <ACol :span="10" class="h-full">
        <EngineeringInstruction ref="engineeringInstructionRef" :engineering-table-data="props.engineeringTableData" />
      </ACol>
    </ARow>
  </div>
</template>

<style lang="scss" scoped></style>
